from gi.repository import Gdk

# 键盘事件有关函数，设置易读的快捷键

def get_keyevent_name(key_event):
        if key_event.is_modifier != 0:
            return ""

        key_modifiers = get_key_event_modifiers(key_event)
        key_name = get_key_name(key_event.keyval)

        if len(key_modifiers) == 0:
            return key_name
        
        name = ""
        for modifier in key_modifiers:
            name += modifier + " + "
        
        name += key_name
        return name
    

def get_key_event_modifiers(key_event):
        modifiers = []

        if key_event.state & Gdk.ModifierType.CONTROL_MASK != 0:
            modifiers.append("Ctrl")

        if key_event.state & Gdk.ModifierType.SUPER_MASK != 0:
            modifiers.append("Super")

        if key_event.state & Gdk.ModifierType.HYPER_MASK != 0:
            modifiers.append("Hyper")

        if key_event.state & Gdk.ModifierType.MOD1_MASK != 0:
            modifiers.append("Alt")

        if key_event.state & Gdk.ModifierType.SHIFT_MASK != 0:
            modifiers.append("Shift")

        return modifiers

def get_key_name(keyval):
        key_unicode = Gdk.keyval_to_unicode(Gdk.keyval_to_lower(keyval))

        if key_unicode == 0:  # function keys at top line of keyboard
            keyname = Gdk.keyval_name(keyval)

            # Gdk.keyval_name will return null when user's hardware got KEY_UNKNOWN from hardware.
            # So, we need return empty string to protect program won't crash later.
            if keyname == None:
                return ""

            if keyname == "ISO_Left_Tab":
                return "Tab"
            else:
                return keyname

        else:
            if key_unicode == 13:
                return "Enter"
            elif key_unicode == 9:
                return "Tab"
            elif key_unicode == 27:
                return "Esc"
            elif key_unicode == 8:
                return "Backspace"
            elif key_unicode == 127:
                return "Delete"
            elif key_unicode == 32:
                return "Space"
            else:
                return chr(key_unicode)